package com.android.wake_up_enable_hotspot;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.android.wake_up_enable_hotspot.databinding.ActivityMainBinding;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 热点开启方式参考：
 * android(6.0，11.0)开启wifi热点
 * https://blog.csdn.net/liangdong1002/article/details/127880692
 */
public class MainActivity extends AppCompatActivity {

    private static final String[] NEEDS_PERMISSION = {"android.permission.ACCESS_FINE_LOCATION", "android.permission.BLUETOOTH"};
    private static final int REQUEST_BT_DEVICE = 1155;
    private static final int REQUEST_CODE_LOCATION = 1122;
    private static final int REQUEST_CODE_SETTINGS = 1133;
    private ActivityMainBinding binding;
    private BluetoothAdapter mBluetoothAdapter;
    private String target_device_address;
    private String target_device_name;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding inflate = ActivityMainBinding.inflate(getLayoutInflater());
        this.binding = inflate;
        setContentView(inflate.getRoot());
        this.binding.enableSw.setChecked(SpUtil.isFeaturesEnable(this));
        this.binding.enableSw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // from class: com.baidu.unlock_open_hotspot.MainActivity.1
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SpUtil.setFeaturesEnable(MainActivity.this, isChecked);
            }
        });
        loadData();
        this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!isAllPermissionGranted()) {
            ActivityCompat.requestPermissions(this, NEEDS_PERMISSION, REQUEST_CODE_LOCATION);
        }
    }

    private boolean isAllPermissionGranted() {
        for (String permission : NEEDS_PERMISSION) {
            if (ContextCompat.checkSelfPermission(this, permission) != 0) {
                return false;
            }
        }
        return true;
    }

    private void loadData() {
        this.target_device_name = SpUtil.getSavedBtName(this);
        this.target_device_address = SpUtil.getSavedBtMac(this);
        this.binding.carBtAddressTv.setText("名称=[" + this.target_device_name + "] 地址=[" + this.target_device_address + "]");
    }

    public void enableHotspot(View view) {
        requestSystemSetPermissionAndOptionWifiAp();
        Toast.makeText(this, "热点已开启，WiFi已关闭", Toast.LENGTH_SHORT).show();
    }

    public void disableHotspot(View view) {
        WifiApUtil.setWifiApEnabled(false);
        Toast.makeText(this, "热点已关闭，WiFi已开启", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_LOCATION) {
            if (isAllPermissionGranted()) {
                if (!Settings.System.canWrite(this)) {
                    new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("我们的应用需要您授权\"修改系统设置\"的权限,请点击\"确定\"跳转开启")
                            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { // from class: com.baidu.unlock_open_hotspot.MainActivity.3
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(MainActivity.this, "没有授予相关权限，部分功能将受影响", Toast.LENGTH_SHORT).show();
                                    MainActivity.this.finish();
                                }
                            }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { // from class: com.baidu.unlock_open_hotspot.MainActivity.2
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent("android.settings.action.MANAGE_WRITE_SETTINGS", Uri.parse("package:" + MainActivity.this.getPackageName()));
                                    MainActivity.this.startActivityForResult(intent, MainActivity.REQUEST_CODE_SETTINGS);
                                }
                            }).setCancelable(false).show();
                    return;
                }
                return;
            }
            Toast.makeText(this, "没有授予相关权限，部分功能将受影响", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        BluetoothDevice scanDevice;
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SETTINGS) {
            loadData();
        } else if (requestCode != REQUEST_BT_DEVICE || data == null || (scanDevice = (BluetoothDevice) data.getParcelableExtra("android.bluetooth.device.extra.DEVICE")) == null) {
        } else {
            if (ActivityCompat.checkSelfPermission(this, "android.permission.BLUETOOTH_CONNECT") != 0 && Build.VERSION.SDK_INT >= 31) {
                ActivityCompat.requestPermissions(this, new String[]{"android.permission.BLUETOOTH_CONNECT"}, 0);
                return;
            }
            String name = scanDevice.getName();
            String address = scanDevice.getAddress();
            SpUtil.saveBtInfo(this, name, address);
            loadData();
            KLog.e();
        }
    }

    public void requestSystemSetPermissionAndOptionWifiAp() {
        if (!Settings.System.canWrite(this)) {
            Toast.makeText(this, "没有授予相关权限，部分功能将受影响", Toast.LENGTH_SHORT).show();
        } else {
            WifiApUtil.setWifiApEnabled(true);
        }
    }

    public void setCarWiFi(View view) {
        startActivityForResult(new Intent(this, BtDeviceListActivity.class), REQUEST_BT_DEVICE);
//        ProgressDialog dialog = new ProgressDialog(this);
//        dialog.setTitle("title");
//        dialog.setMessage("message");
//        List<BleDevice> list = new ArrayList<>();
//        BleManager.getInstance().scan(new BleScanCallback() {
//            @Override
//            public void onScanFinished(List<BleDevice> scanResultList) {
//                dialog.dismiss();
//                if (list.isEmpty()) {
//                    Toast.makeText(MainActivity.this, "未搜索到BLE设备", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                List<String> items = new ArrayList<>();
//                for (BleDevice bleDevice : list) {
//                    String deviceName = bleDevice.getName();
//                    if (TextUtils.isEmpty(deviceName)) {
//                        continue;
//                    }
//                    String deviceMac = bleDevice.getMac();
//                    int rssi = bleDevice.getRssi();
//                    items.add(deviceName + "【" + deviceMac + "】" + rssi);
//                }
//                String[] array = items.toArray(new String[0]);
//                new AlertDialog.Builder(MainActivity.this)
//                        .setItems(array, new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                BleDevice bleDevice = list.get(which);
//                                String deviceName = bleDevice.getName();
//                                String deviceMac = bleDevice.getMac();
//                                Toast.makeText(MainActivity.this, "position: " + which + " " + deviceName + " " + deviceMac, Toast.LENGTH_SHORT).show();
//                            }
//                        })
//                        .show();
//                System.out.println();
//            }
//
//            @Override
//            public void onScanStarted(boolean success) {
//                dialog.show();
//                list.clear();
//            }
//
//            @Override
//            public void onScanning(BleDevice bleDevice) {
//                list.add(bleDevice);
//            }
//        });
    }

    public void autoBootSet(View view) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.mainscreen.MainScreenActivity"));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "跳转华为手机管家失败，请自行设置自启与后台白名单", Toast.LENGTH_SHORT).show();
        }
    }

    public void startBgService(View view) {
        startService(new Intent(this, BootCompleteService.class));
    }

    public void stopBgService(View view) {
        stopService(new Intent(this, BootCompleteService.class));
    }
}